package com.yiguantong.police.update;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSONObject;
import com.yiguantong.police.R;
import com.yiguantong.police.ui.activity.MainActivity;
import com.yiguantong.police.ui.utils.Util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UpdateTask {

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    public void execute(Context context) {
        if (isNetworkConnected(context)) {
            new WorkTask(context).execute();
        } else {
            new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                    .setContentText("系统提示:手机网络连接失败，请打开网络")
                    .show();
        }
    }

    private boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        }
        return false;
    }

    private class WorkTask extends AsyncTask<Void, Void, Result> {
        private Context context;
        private SweetAlertDialog dialog;

        private WorkTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE);
            dialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
            dialog.setContentText("版本更新");
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Result doInBackground(Void... params) {
            Result result = null;
            try {
                OkHttpClient mOkHttpClient = new OkHttpClient();
                JSONObject object = new JSONObject();
                object.put("appid", context.getApplicationInfo().processName);
                object.put("version", Util.getVersionName());
                RequestBody body = RequestBody.create(JSON, object.toJSONString());
                Request request = new Request.Builder()
                        .url(context.getString(R.string.apk_version_url))
                        .post(body)
                        .build();

                Response response = mOkHttpClient.newCall(request).execute();
                String text = response.body().string();
                Log.d("updateTask", text);
                JSONObject.parse(text);
                result = JSONObject.parseObject(text, Result.class);

            } catch (Exception e) {
                Log.e("版本更新失败", Log.getStackTraceString(e));
                result = new Result();
                result.setCode(0);
                result.setMsg(e.getMessage());
            }

            return result;
        }

        @Override
        protected void onPostExecute(Result result) {
            super.onPostExecute(result);
            dialog.dismiss();

            if (result.getCode() != 200) {
                new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                        .setContentText("版本更新失败" + result.getMsg())
                        .show();
                ((Activity) context).finish();
                context.startActivity(new Intent(context, MainActivity.class));
                return;
            }

            if (result.getData() != null && "1".equals(result.getData().getStatus())) {
                requestPermission(context);
                try {
                    Result.Version version = result.getData();
                    String versionName = version.getVersion();
                    String versionDesc = version.getNote();
                    final String url = version.getUrl();

                    SweetAlertDialog confirmUpdate = new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("版本更新内容")
                            .setContentText("版本升级" + versionName + "\n" + versionDesc.replaceAll("\\\\n", "\n"))
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    new DowloadTask(context).execute(url);
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            });

                    confirmUpdate.show();

                } catch (Exception e) {
                    Log.e("版本更新失败", Log.getStackTraceString(e));

                    new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                            .setContentText("版本更新失败" + e.getMessage())
                            .show();
                }
                return;
            }
            ((Activity) context).finish();
            context.startActivity(new Intent(context, MainActivity.class));
            return;
        }

    }

    private class DowloadTask extends AsyncTask<String, String, Result> {
        private Context context;
        private SweetAlertDialog dialog;

        private DowloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            dialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE);
            dialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
            dialog.setContentText("下载新版本");
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Result doInBackground(String... params) {

            Result result = new Result();
            try {
                File file = getFileFromServer(params[0]);
                result.setFile(file);

            } catch (Exception e) {
                Log.e("版本更新失败", Log.getStackTraceString(e));
                result.setCode(0);
                result.setMsg(e.getMessage());
            }

            return result;
        }

        @Override
        protected void onPostExecute(Result result) {
            super.onPostExecute(result);
            dialog.dismiss();

            if (result.getCode() != 1) {
                new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("版本更新失败")
                        .setContentText("新版本下载失败" + result.getMsg())
                        .show();
                return;
            }

            File file = result.getFile();

            if (null == file) {
                new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("版本更新失败")
                        .setContentText("下载新版本失败")
                        .show();
                return;
            }
            installApk(file);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            dialog.setContentText(mb(values[0]) + "/" + mb(values[1]) + "MB");
        }

        private String mb(String bytes) {
            return new BigDecimal(bytes).divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP).toString();
        }

        public File getFileFromServer(String path) throws Exception {
            //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return null;
            }

            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                int contentLength = conn.getContentLength();

                File file = new File(Environment.getExternalStoragePublicDirectory("Download"), path.substring(path.lastIndexOf("/") + 1));
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }

                out = new BufferedOutputStream(new FileOutputStream(file));
                in = new BufferedInputStream(conn.getInputStream());

                int len = -1;
                int total = 0;
                byte[] buffer = new byte[4096];

                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                    total += len;

                    publishProgress(String.valueOf(total), String.valueOf(contentLength));
                }

                return file;
            } finally {
                try {
                    in.close();
                } catch (Exception e) {
                    Log.e("下载新版本失败", Log.getStackTraceString(e));
                }

                try {
                    out.close();
                } catch (Exception e) {
                    Log.e("下载新版本失败", Log.getStackTraceString(e));
                }
            }
        }

        protected void installApk(File file) {
            //判断是否是AndroidN以及更高的版本
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri contentUri = FileProvider.getUriForFile(context, "com.yiguantong.police.fileprovider", file);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            context.startActivity(intent);
        }
    }

    //设备API大于6.0时，主动申请权限
    private void requestPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }
        }
    }
}
